package com.tuanproject.controller;

import java.sql.Date;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tuanproject.business.EventsBusiness;
import com.tuanproject.model.Events;
import com.tuanproject.util.SendMailUtil;

/**
 * 
 * @author TuanLe
 * 
 */
@RequestMapping("/events")
@Controller
public class EventsController {

	@Autowired
	EventsBusiness eventsBusiness;
	@Autowired
	SendMailUtil sendMailUtil;

	@RequestMapping(value = "")
	public String list(@ModelAttribute Events events, Model uiModel,
			HttpServletRequest request) {
		String ip = request.getParameter("ip");
		String port = request.getParameter("port");
		String method = request.getParameter("method");
		String pattern = request.getParameter("pattern");
		String fromDate = request.getParameter("fromDate");
		String toDate = request.getParameter("toDate");
		ip = ip != null ? ip : "";
		port = port != null ? port : "";
		method = method != null ? method : "";
		pattern = pattern != null ? pattern : "";
		List<Events> list;
		try {
			list = eventsBusiness.getEventsFilter(ip, port, method, pattern,
					fromDate, toDate);
			uiModel.addAttribute("ip", ip);
			uiModel.addAttribute("port", port);
			uiModel.addAttribute("method", method);
			uiModel.addAttribute("pattern", pattern);
			uiModel.addAttribute("fromDate", fromDate);
			uiModel.addAttribute("toDate", toDate);
			if (list.size() > 0) {
				uiModel.addAttribute("listEvents", list);
				uiModel.addAttribute("listSize", list.size());

				sendMailUtil.sendMail("Dear Mr. Tuan", uiModel.asMap());
			} else {
				uiModel.addAttribute("msg", "Data not found");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "index";
	}

	@RequestMapping(value = "/defectattack")
	public void autoDefect(Model uiModel, HttpServletRequest request) {

		String fromDate = request.getParameter("fromDate");
		String toDate = request.getParameter("toDate");
		try {
			List<Events> list = eventsBusiness.getEventsByTime(fromDate, toDate);
			if (list.size() > 0) {
				uiModel.addAttribute("listEvents", list);
				uiModel.addAttribute("listSize", list.size());
				sendMailUtil.sendMail("Dear Mr. Tuan", uiModel.asMap());
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
